from ccpm.pmbase import PluginBase, PmUtil
from ccpm.glan import Lan
import os
from ccpm.constants import Constant
import sys
import json
from ccpm.plugins.install import InstallPlugin


class UpgradePlugin(PluginBase):

    PLUGIN_INFO = dict(
        name="upgrade",
        help="update the modules by packcfg.json <dependencies> key!"
    )

    def __init__(self):
        if not hasattr(self, "_inc"):
            self._inc = super().__init__(self.PLUGIN_INFO)
        return self._inc

    def __suc(self):
        self.logger.info(Lan.p(self.name, "INFO_UPGRADE_SUCCESS"))

    def __chk_plugin_denpendencies(self):
        p_list = self._p_info["dependencies"]
        for p in p_list:
            os.system("ccpm install %s" % p)

    def __chk_plugin_devtool(self):
        devtool = self._p_info.get("dev-tool")
        if devtool:
            tfile = InstallPlugin().install_plugin(os.getcwd(), devtool)
            hook_script = PmUtil.path_compatible(
                "./%s/hook.sh" % (PmUtil.get_plugin_name(devtool)))
            if os.path.isfile(hook_script):
                os.system("sh %s" % hook_script)
            self.append_rm_tmp(tfile)

    def __init_env(self):
        (isr, p_conf) = PmUtil.is_package_projpath(os.getcwd())
        if not (isr):
            self.err_break(
                Lan.p(self.name, "ERR_LOCALENV_NOCFG"))
        ret = []
        ret = p_conf.get("dependencies")
        self._p_info = p_conf
        return ret

    def parser_config(self, argparser):
        super().parser_config(argparser)

    def run(self, argpars):
        super().run(argpars)
        self.__init_env()
        # chk devtool
        self.__chk_plugin_devtool()
        # chk dependencies
        self.__chk_plugin_denpendencies()
        self.logger.info(Lan.p(self.name, "INFO_UPGRADE_SUCCESS"))
        self.rm_temp()


__all__ = [
    "UpgradePlugin"
]
